<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/13
 * Time: 14:50
 */

namespace App\CronTask;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\HttpClient\HttpClient;

/**
 * 更新符文数据
 * Class RunesCron
 * @package App\CronTask
 */
class RunesCron extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        //return '@daily';
        return '* * * */1 *';
    }
    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        return 'runes';
    }

    static function run(\swoole_server $server, int $taskId, int $fromWorkerId, $flags = null)
    {
        // TODO: Implement run() method.
        $table = 'siam_lolrunes';
        $url = UrlEnums::FJURL.UrlEnums::LOL_RUNES_PATH.'?version=2';
        $client = new HttpClient($url);
        list($s1, $s2) = explode(' ', microtime());
        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
        $option = [
            'path'      => UrlEnums::LOL_RUNES_PATH,
            'api_time'  => $microtime
        ];
        $header = Auth::getInstance()->header($option);
        $client->setHeaders($header,true,false);
        $response = $client->get();
        $content = $response->getBody();
        $data = json_decode($content,true);
        MysqlPool::invoke(function (MysqlObject $db)use($data,$table){
            if( $data['code'] == 200 && !empty($data['data']) ){
                foreach ( $data['data'] as $item ){
                    $raw = $db->where('rune_id',$item['rune_id'])->getOne($table);
                    if( !$raw ){
                        $db->insert($table,$item);
                    }
                }
            }
        });
    }
}